package cn.dyw.cloudmusic.http;

import cn.dyw.cloudmusic.config.MybatisConfig;
import cn.dyw.cloudmusic.dao.AlMapper;
import cn.dyw.cloudmusic.dao.ArMapper;
import cn.dyw.cloudmusic.dao.MusicMapper;
import cn.dyw.cloudmusic.http.model.Params;
import cn.dyw.cloudmusic.music.vo.Single;
import cn.dyw.cloudmusic.music.vo.Songs;
import com.alibaba.fastjson.JSON;
import okhttp3.Response;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * @author: dyw770
 * @Date: 2019/1/16 22:08
 * @Description: TODO
 */
public class SingleSaveHandle implements SaveHandle {

    @Override
    public void save(Response response, Params p) {
        try {
            Single single = JSON.parseObject(response.body().string(), Single.class);

            SqlSession session = MybatisConfig.getSession();
            MusicMapper musicMapper = session.getMapper(MusicMapper.class);
            AlMapper alMapper = session.getMapper(AlMapper.class);
            ArMapper arMapper = session.getMapper(ArMapper.class);

            List<Songs> songs = single.getResult().getSongs();
            songs.forEach(song -> {
                musicMapper.insertVo(song);
                alMapper.insertVo(song.getAl(), song);
                arMapper.insertList(song.getAr(), song);
            });
            session.commit();
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
